import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import { Loading } from 'element-ui'
import store from '@/store'

Vue.use(VueRouter)

const router = new VueRouter({
  base: '/',
  mode: 'history',
  routes,
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { y: 0, behavior: 'smooth' }
  },
})

// loading实例
let loadingInstance = null

// 全局路由守卫
router.beforeEach(async (to, from, next) => {
  // token
  let token = store.state.user.token
  loadingInstance = Loading.service({
    lock: true,
    text: '加载中',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  // 未登录
  if (!token) {
    const toPath = to.path
    // 未登录路由拦截
    if (toPath.indexOf('/person-center') != -1) {
      // 存储路由拦截的路由，登陆成功后进行跳转
      next(`/login?redirect=${toPath}`)
    } else {
      next()
    }
  } else {
    next()
  }
})
router.afterEach((to, from) => {
  loadingInstance.close()
  document.title = '绿色出行 - ' + to.meta?.title
})

export default router
